#include "headers/process_killer.h"
#include "../adt/headers/linked_list.h"
#include "../multitasking/headers/task.h"
#include "../api/headers/errors.h"
task_t* killer_task = NULL;
extern task_t* current_task;
extern linked_list_type* task_list;
linked_list_type* to_be_killed = NULL;
extern task_t* focused_task;

void process_killer()
{
	killer_task = current_task;
	
	to_be_killed = create_linked_list(false);
	task_t* tmp;
	u32int killed_pid;
	u32int index;
	if(getLastError() != NO_ERROR)
		K_PANIC("Error creating to_be_killed list");
	printf("Process killer initialized\n\n");
	
	for(;;)
	{
		block_process(killer_task, RES_LIST, to_be_killed);
		while(get_number_of_list_elements(to_be_killed))
		{
			asm volatile ("cli");
			tmp = get_first_from_list(to_be_killed);
			remove_from_list(0, to_be_killed);

			if(tmp->id<= 3)
			{
				printf("Impossible to kill system process\n");
				
				asm volatile ("sti");
				continue;
			}
			
			if(tmp == focused_task)
				makeVirtualConsoleFocused(killer_task);
			
			killed_pid = tmp->id;
			index = find_in_list(tmp, task_list);
			if(index != LIST_ERROR)
			{
				remove_from_list(index, task_list);
			}
			asm volatile ("sti");
			
			kill_process(tmp);
			
			if(getLastError() == NO_ERROR)
				printf("Process %d was sucessfully killed\n", killed_pid);
			else
				printf("Error: Could not kill process %d\nLast error: %s\n", killed_pid, getLastErrorMessage());
		}
	}
	
	
}